package com.zzyl.nursing.service.impl;

import java.time.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataDto;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.FamilyMemberDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataVoo;
import com.zzyl.nursing.vo.FamilyMemberVO;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.health.HealthDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderServiceImpl elderService;
    @Autowired
    private DeviceServiceImpl deviceService;
    @Autowired
    private IoTDAClient client;

    static List<String> DEFAULT_NICK_NAME = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId,openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if(ObjectUtil.isEmpty(familyMember)){
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder()
                    .openId(openid)
                    .build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember,phone);

        //6. 把用户的信息封装到token,返回
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",familyMember.getName());
        claims.put("userId",familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    /**
     *  绑定家人
     * @param dto
     * @return
     */
    @Override
    public int add(FamilyMemberDto dto) {
        Long userId = UserThreadLocal.getUserId();
        String idCard = dto.getIdCard();
        Elder one = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, idCard)
                .one();
        if (one == null){
            throw new RuntimeException("该老人不存在");
        }
        FamilyMemberEder familyMemberEder = new FamilyMemberEder();
        familyMemberEder.setElderId(one.getId());
        familyMemberEder.setFamilyMemberId(userId);
        familyMemberEder.setRemark(dto.getRemark());
        familyMemberEder.setCreateTime(DateUtils.getNowDate());
        // insert into family_member_eder (family_member_id, elder_id, create_time, update_time, create_by, update_by, remark)
        familyMemberMapper.add(familyMemberEder);
        return 1;
    }

    /**
     *  查询家人列表
     * @return
     */
    @Override
    public List<FamilyMemberEder> my() {
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberEder> list = familyMemberMapper.my(userId);

        return list;
    }

    @Override
    public List<FamilyMemberVO> listByPage() {
        Long userId = UserThreadLocal.getUserId();
        List<FamilyMemberVO> familyMemberVOS = familyMemberMapper.listByPage(userId);


        return familyMemberVOS;
    }

    @Override
    public HealthDataVo QueryDevicePropertyStatus(DeviceDto dto) {
        String productKey = dto.getProductKey();
        Device one = deviceService.lambdaQuery()
                .eq(Device::getProductKey, productKey)
                .eq(Device::getDeviceName, dto.getDeviceName())
                .one();
        String iotId = one.getIotId();

        ShowProductRequest request1 = new ShowProductRequest();
        request1.withProductId(one.getProductKey());

        ShowProductResponse response1 = client.showProduct(request1);
        List<ServiceProperty> properties1 = response1.getServiceCapabilities().get(0).getProperties();
//        String dataType = response1.getServiceCapabilities().get(0).getProperties().get(0).getDataType();
//        String name = response1.getServiceCapabilities().get(0).getProperties().get(0).getDescription();
//        String unit = response1.getServiceCapabilities().get(0).getProperties().get(0).getUnit();


        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        System.out.println("response = " + JSONUtil.toJsonStr( response));
        String eventTime = null;
        try {
            // 添加完整的空值检查
            if (response.getShadow() == null ||
                    response.getShadow().isEmpty() ||
                    response.getShadow().get(0) == null ||
                    response.getShadow().get(0).getReported() == null) {
                throw new RuntimeException("当前没有该老人的监测数据");
            }
            eventTime = response.getShadow().get(0).getReported().getEventTime();
        } catch (Exception e) {
            // 统一处理所有异常情况，返回明确提示信息
            throw new RuntimeException("当前没有该老人的监测数据");
        }


        long timestamp = convertToTimestamp(eventTime);
        log.info("timestamp = " + timestamp);


        LinkedHashMap<String,Object> properties = (LinkedHashMap<String, Object>) response.getShadow().get(0).getReported().getProperties();
        List<Map<String,Object>> list = new ArrayList<>();
        // 用于记录已处理的properties的key
        List<Map<String, Object>> list1 = new ArrayList<>();
         // 用于记录已处理的identifier，确保每条数据只出现一次
        Set<String> processedIdentifiers = new HashSet<>();

        for (ServiceProperty serviceProperty : properties1) {
            String dataType = serviceProperty.getDataType();
            String name = serviceProperty.getDescription();
            String unit = serviceProperty.getUnit();
            String propertyName = serviceProperty.getPropertyName();
            properties.forEach((k,v)->{
                // 当properties的key与ServiceProperty的关联字段匹配，且未处理过时才添加
                if (k.equals(propertyName) && !processedIdentifiers.contains(k)) {


                    Map<String, Object> map = new HashMap<>();
                    list.add(map);
                    map.put("identifier", k);
                    map.put("value", v);
                    map.put("time", timestamp);
                    map.put("dataType", dataType);
                    map.put("name", name);
                    map.put("unit", unit);
                    list1.add(map);
                    processedIdentifiers.add(k); // 标记为已处理
                }
            });

        }

        HealthDataVo healthDataVo = new HealthDataVo();
        Map<String,Object> map = new HashMap<>();
        map.put("propertyStatusInfo",list);
        healthDataVo.setList(map);

        return  healthDataVo;
    }

    @Override
    public Integer deleteFamilyMemberElderById(Long id) {
        return familyMemberMapper.deleteFamilyMemberElderById(id);


    }

    public static long convertToTimestamp(String timeStr) {
        // 定义时间格式器，匹配输入的时间字符串格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");

        // 先解析为LocalDateTime，再转换为UTC时区的Instant
        LocalDateTime localDateTime = LocalDateTime.parse(timeStr, formatter);
        Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

        // 转换为毫秒级时间戳
        return instant.toEpochMilli();
    }


    /**
     * 新增或修改用户
     * @param familyMember
     * @param phone
     */
    private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //1. 判断新的手机跟数据库中保存的手机号是否一致
        if(ObjectUtil.notEqual(familyMember.getPhone(),phone)){
            familyMember.setPhone(phone);
        }

        //2. id是否存在，如存在，就修改
        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }

        //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
        int index = (int)(Math.random() * DEFAULT_NICK_NAME.size());
        String nickName = DEFAULT_NICK_NAME.get(index)+ phone.substring(phone.length()-4);
        familyMember.setName(nickName);
        save(familyMember);

    }

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

    /**
     * 按天统计查询指标数据
     * @param dto
     * @return
     */
    @Override
    public List<DeviceDataVoo> queryDeviceDataListByDay(DeviceDataDto dto) {
        return familyMemberMapper.queryDeviceDataListByDay(dto);
    }

    @Override
    public List<DeviceDataVoo> queryDeviceDataListByWeek(DeviceDataDto dto) {
        return familyMemberMapper.queryDeviceDataListByWeek(dto);
    }


}
